package logic

import (
	"ahutoj/web/io/constanct"
	"ahutoj/web/io/response"
	"ahutoj/web/utils"
	"os"
	"strings"

	"github.com/gin-gonic/gin"
)
var passSuffix = []string{"in", "out", "zip"}

func CheckSuccessFile(filename string) bool {
	logger := utils.GetLogInstance()
	filenames := strings.Split(filename, ".")
	logger.Debugf("filenames:%+v", filenames)
	if len(filenames) == 1 {
		return false
	}
	suffix := filenames[len(filenames)-1]
	for _, data := range passSuffix {
		if data == suffix {
			return true
		}
	}
	return false
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func GetPath(ctx *gin.Context) string {
	pid := ctx.Param("pid")
	if pid == "" {
		return ""
	}
	//判断文件夹存在 这要求我们创建题目的时候 必须创建一个对应的文件夹
	return utils.GetConfInstance().DataPath + "/" + pid
}

func BuildFilePathResp(ctx *gin.Context, filepath string) (interface{}, error) {
	logger := utils.GetLogInstance()
	files, err := os.ReadDir(filepath)
	if err != nil {
		logger.Errorf("call ReadDir faile,filepath=%s err=%s", filepath, err.Error())
		return response.CreateResponse(constanct.InvalidParamCode), nil
	}
	resp := response.GetFileListResp{}
	resp.Data = make([]response.FileItem, 0)
	for _, file := range files {
		fileinfo, _ := file.Info()
		resp.Data = append(resp.Data, response.FileItem{
			Filename: file.Name(),
			FileSize: fileinfo.Size(),
			FileType: utils.GetFileType(file.Name()),
		})
	}
	response.CreateResponse(constanct.SuccessCode)
	return resp, nil
}
